package com.zgys.mes.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zgys.mes.client.dto.UserDto;
import com.zgys.mes.util.error.RtErrorEnum;
import com.zgys.mes.util.error.RtException;
import com.zgys.mes.util.error.RtResponse;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;

/**
 * Created by jiafe on 2018/5/23.
 */
public class RestTemplateClient {
    private String ip;
    private String port;
    private RestTemplate restTemplate;
    private ObjectMapper mapper;

    public RestTemplateClient(String ip,String port) {
        this.ip = ip;
        this.port = port;
        this.restTemplate = new RestTemplate();
        mapper = new ObjectMapper();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(fmt);
    }

    public UserDto getUser(int userId) {
        RtResponse response = restTemplate.getForObject("http://"+ip+":"+port+"/baseUrl/User/{userId}", RtResponse.class, userId);
        return getResponseContent(response, UserDto.class);
    }

    public<T> T getResponseContent(RtResponse response, Class<T> clazz) {
        if (response.getCode() == RtErrorEnum.SUCCESS.getCode()) {
            T obj = mapper.convertValue(response.getContent(), clazz);
            return obj;
        }else {
            throw new RtException(response);
        }
    }

}
